package com.gateway.predicate;

import org.springframework.cloud.gateway.handler.predicate.AbstractRoutePredicateFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;

import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

@Component
public class CustomRoutePredicateFactory extends AbstractRoutePredicateFactory<CustomRoutePredicateFactory.Config>{

    public CustomRoutePredicateFactory() {
        super(CustomRoutePredicateFactory.Config.class);
    }

    /**
     * 读取配置文件的参数值，赋值到配置类中的属性上
     * */
    @Override
    public List<String> shortcutFieldOrder(){
        return Arrays.asList("name");
    }
    @Override
    public Predicate<ServerWebExchange> apply(CustomRoutePredicateFactory.Config config) {
        return new Predicate<ServerWebExchange>() {
            @Override
            public boolean test(ServerWebExchange serverWebExchange) {
                if(config.getName().equals("张三")) {
                    System.out.println("自定义通断言过，放行");
                    return true;
                }
                System.out.println("自定义断言不通过，不予放行");
                return false;
            }
        };
    }

    public static class Config{
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }

        public Config(){}
    }
}
